package com.lxc.demos;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.lxc.demos.opensource.c2dm.C2DMActivity;
import com.lxc.demos.util.c2dm.C2DMBaseReceiver;
import com.lxc.demos.util.c2dm.C2DMConfig;
import com.lxc.demos.util.c2dm.C2DMessaging;

public class C2DMReceiver extends C2DMBaseReceiver {
	
	public static String TAG = "C2DM";
	
	public C2DMReceiver(){
		super(C2DMConfig.C2DM_SENDER);
	}

	public C2DMReceiver(String senderId) {
		super(senderId);
	}

	@Override
	protected void onMessage(Context context, Intent intent) {
		Bundle extras = intent.getExtras();
		String accountName = extras.getString(C2DMConfig.C2DM_ACCOUNT_EXTRA);
		String message = extras.getString(C2DMConfig.C2DM_MESSAGE_EXTRA);
		Log.d(TAG, C2DMConfig.C2DM_ACCOUNT_EXTRA + " = " + accountName);
		String msg = accountName+":"+message;
//      Toast.makeText(C2DMApplication.getApplication(), msg, Toast.LENGTH_LONG).show();
		sendNotification(context,msg);
	}

	@Override
	public void onError(Context context, String error) {

	}
	
	/**
	 * Register or unregister based on phone sync settings.
	 * Called on each performSync by the SyncAdapter.
	 * @param context
	 */
	public static void refreshAppC2DMRegistrationState(Context context){
		//Detemine if there are any auto-syncable accounts.If there are ,make sure we are
		//registered with the C2DM serviers. If not,unregister the application.
		Log.d(TAG,"refreshAppC2DMRegistrationState");
		String registrationId = C2DMessaging.getRegistrationId(context);
		if(registrationId == null || registrationId.equals("")){
			C2DMessaging.register(context, C2DMConfig.C2DM_SENDER);
		}else{
			Log.d(TAG,"have registrationId = " + registrationId);
		}
	}
	
	private void sendNotification(Context context,CharSequence msg){
		NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.icon, msg, System.currentTimeMillis());
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		Intent intent = new Intent(context,C2DMActivity.class);
		intent.putExtra("msg", msg);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
		PendingIntent contentIntent = PendingIntent.getActivity(context, R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		notification.setLatestEventInfo(context, "contentTitle", "contentText", contentIntent);
		int nId = (int) (System.currentTimeMillis()%Integer.MAX_VALUE);
		notificationManager.notify(nId, notification);
	}

}
